# -*- coding: utf-8 -*-
from django.conf import settings
import gdata.calendar.service
import gdata.service
import gdata.calendar
import atom.data
import gdata.data
import gdata.calendar.client
import gdata.calendar.data
import time


class Client:
    def __init__(self):
        self.__client = self.__login(settings.CALENDAR_USER_EMAIL, settings.CALENDAR_USER_PASSWORD, 'Auto search')
        self.__TRIES = 5

    def __login(self, login, password, app_name):
        client = gdata.calendar.client.CalendarClient()
        client.source = app_name
        ok = False
        i = 0
        while ok != True:
            try:
                client.ClientLogin(login, password, app_name)
                ok = True
            except gdata.service.CaptchaRequired:
                i += 1
            except gdata.service.BadAuthentication:
                i += 1
            except gdata.service.Error:
                i += 1
        return client

    def __create_event(self, title=u"", content=u""):
        event = gdata.calendar.data.CalendarEventEntry()
        event.title = atom.data.Title(text=title)
        event.content = atom.data.Content(text=content)
        start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())
        end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600))
        event.when.append(gdata.data.When(start=start_time, end=end_time))
        return event

    def __get_calendar_uri(self, calendar_id):
        return "http://www.google.com/calendar/feeds/" + calendar_id + "/private/full/"

    def __insert_event(self, event, calendar_id):
        # return self.__error_handler(self.__client.InsertEvent, event, self.__get_calendar_uri(calendar_id))
        return self.__client.InsertEvent(event, self.__get_calendar_uri(calendar_id))

    def add_event_to_calendar(self, calendar_id, title=u"", content=u""):
        event = self.__create_event(title, content)
        return self.__insert_event(event, calendar_id)

    def __error_handler(self, f, *args, **kwargs):
        res = False
        i = 0
        while not res:
            if i < self.__TRIES:
                try:
                    res = f(*args, **kwargs)
                except gdata.service.RequestError, e:
                    i += 1
                    print(u'RequestError при выполнении %s' % f.__name__)
                    print('gdata.service.RequestError.status: %s' % e[0]['status'])
                    print('gdata.service.RequestError.body: %s' % e[0]['body'])
                    print('gdata.service.RequestError.reason: %s' % e[0]['reason'])
                except:
                    i += 1
                    print(u'Error при выполнении %s, количество попыток: %d' % (f.__name__, i))
            else:
                break
        if res:
            print(u'Выполнили %s' % f.__name__)
        return res